package com.cvr.project.repertory;

import androidx.lifecycle.MutableLiveData;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

/**
 * _ooOoo_
 * o8888888o
 * 88" . "88
 * (| -_- |)
 * O\ = /O
 * ____/`---'\____
 * .   ' \\| |// `.
 * / \\||| : |||// \
 * / _||||| -:- |||||- \
 * | | \\\ - /// | |
 * | \_| ''\---/'' | |
 * \ .-\__ `-` ___/-. /
 * ___`. .' /--.--\ `. . __
 * ."" '< `.___\_<|>_/___.' >'"".
 * | | : `- \`.;`\ _ /`;.`/ - ` : | |
 * \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 * `=---='
 * .............................................
 * 佛祖保佑             永无BUG
 *
 * @author :created by master
 * time :2021-6-29 21:58:05
 * 描述：BaseSubscriber
 */
public class BaseSubscriber<T> implements Subscriber<BaseResponse<T>> {
    //异常类
    private ApiException ex;

    private MutableLiveData<BaseResponse<T>> data;

    public BaseSubscriber() {
        data = new MutableLiveData();
    }

    public MutableLiveData<BaseResponse<T>> get() {
        return data;
    }

    public void set(BaseResponse<T> t) {
        this.data.setValue(t);
    }

    public void onFinish(BaseResponse<T> t) {
        set(t);
    }

    @Override
    public void onSubscribe(Subscription s) {
        s.request(1);
    }

    @Override
    public void onNext(BaseResponse<T> t) {
        if (t.getStatus().equals(BaseResponse.CODE_SUCCESS)) {
            onFinish(t);
        } else {
            ex = ExceptionEngine.handleException(new ServerException(t.getStatus(), t.getMsg()));
            getErrorDto(ex, 0);
            //服务到期（因上下文问题 处理逻辑放到接口回调处）
//            if (!t.getCode().equals(BaseResponse.SERVICE_EXPIRE)) {
//                ToastUtils.showShort(t.getMsg());
//            }
        }
    }

    @Override
    public void onError(Throwable t) {
        ex = ExceptionEngine.handleException(t);
        getErrorDto(ex, 1);
    }

    /**
     * 初始化错误的dto
     *
     * @param ex
     */
    private void getErrorDto(ApiException ex, int type) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setStatus(ex.getStatusCode());
        baseResponse.setMsg(ex.getStatusDesc());
        baseResponse.setType(type);
        onFinish((BaseResponse<T>) baseResponse);
    }

    @Override
    public void onComplete() {
//        BaseResponse baseResponse = new BaseResponse();
//        baseResponse.setStatus("3");
//        baseResponse.setMsg("执行完成");
//        onFinish((BaseResponse<T>) baseResponse);
    }
}
